import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/util/val_toast_kit.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

typedef FinishSelected = void Function(List<AssetEntity> value);

class ValPublishContentImagePicker extends StatefulWidget {
  @required final int imageCount; //最大张数
  @required final int lineCount; //每行张数
  final FinishSelected? finishSelected;

  const ValPublishContentImagePicker({super.key, this.imageCount = 3,this.lineCount = 3, this.finishSelected});

  @override
  State<ValPublishContentImagePicker> createState() => ValPublishContentImagePickerState();
}

class ValPublishContentImagePickerState extends State<ValPublishContentImagePicker> {
  final List<AssetEntity> _imageFiles = [];

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      color: Colors.transparent,
      child: Container(
        padding: const EdgeInsets.all(15.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: MasonryGridView.count(
                crossAxisCount: widget.lineCount,
                itemCount: _imageFiles.length == widget.imageCount
                    ? _imageFiles.length
                    : _imageFiles.length + 1,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  if (_imageFiles.length < widget.imageCount && index == _imageFiles.length) {
                    return InkWell(
                      onTap: () => _onPickImage(),
                      child: Container(
                        height: 76,
                        padding: const EdgeInsets.all(0),
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: const Color.fromRGBO(255, 255, 255, 0.5),
                          ),
                          child: Center(
                            child: Image.asset('${ValAssetsName.ASSETS_Message}val_publish_image_picker_bnt.png', width: 32, height: 32, fit:  BoxFit.cover,),
                          ),
                        ),
                      ),
                    );
                  } else {
                    return Stack(
                      children: [
                        Container(
                          padding: const EdgeInsets.only(right: 2),
                          child: InkWell(
                            child: FutureBuilder<AssetEntity>(
                              future: Future(() => _imageFiles[_imageFiles.length < widget.imageCount ? index - 0
                                  : index]),
                              builder: (context, snapshot) {
                                if (snapshot.connectionState ==
                                    ConnectionState.done && snapshot.data != null) {
                                  return Container(
                                  height: 76,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.rectangle,
                                    borderRadius:
                                    BorderRadius.circular(10.0),
                                    image: DecorationImage(
                                      image: AssetEntityImageProvider(snapshot.data!, isOriginal: false),//FileImage(snapshot.data),
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                );
                                } else {
                                  return Container(
                                    decoration: BoxDecoration(
                                      shape: BoxShape.rectangle,
                                      borderRadius:
                                      BorderRadius.circular(6.0),
                                      color: const Color(0xFFF6F7F8),
                                    ),
                                    child: const Center(
                                      child: CupertinoActivityIndicator(),
                                    ),
                                );
                                }
                              },
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () => _deleteImage(
                              _imageFiles.length < widget.imageCount
                                  ? index - 0
                                  : index),
                          child: Container(
                            alignment: Alignment.centerRight,
                            margin: const EdgeInsets.only(top: 2, right: 4),
                            child: Image.asset('${ValAssetsName.ASSETS_HOME}val_home_car_delete_btn.png', width: 25, height: 25, fit:  BoxFit.cover,),
                          ),
                          // child: Container(
                          //   decoration: BoxDecoration(
                          //     borderRadius: BorderRadius.circular(99.0),
                          //     color: Colors.red,
                          //   ),
                          //   padding: EdgeInsets.all(2.0),
                          //   child: Icon(
                          //     Icons.close,
                          //     size: 20.0,
                          //     color: Colors.white,
                          //   ),
                          // ),
                        ),
                      ],
                    );
                  }
                },
                mainAxisSpacing: 4.0,
                crossAxisSpacing: 4.0,
                // itemCount: _imageFiles.length + 1,
              ),
            ),
          ],
        ),
      ),
    );
  }
  /// 选择图片
  _onPickImage() async {
    //超过限制张数
    // if (_imageFiles != null && widget.imageCount > 0 && _imageFiles.length >= widget.imageCount) return;
    PermissionStatus value = await Permission.photos.request();
    if (value == PermissionStatus.permanentlyDenied) {
      ValToastKit.showMessage('You have not authorised this permission.');
      return;
    }
    List<AssetEntity>? assets = await AssetPicker.pickAssets(
      context,
    );
    if (assets == null || assets.isEmpty) return;
    setState(() {
      _imageFiles.addAll(assets);
    });

    if (widget.finishSelected != null) {
      widget.finishSelected!(_imageFiles);
    }
  }
  /// 删除图片
  _deleteImage(int index) {
    if (_imageFiles == null || _imageFiles.length <= index) return;
    setState(() {
      _imageFiles.removeAt(index);
    });

    if (widget.finishSelected != null) {
      widget.finishSelected!(_imageFiles);
    }
  }

  deleteAllImage() {
    setState(() {
      _imageFiles.clear();
    });

    if (widget.finishSelected != null) {
      widget.finishSelected!(_imageFiles);
    }
  }
}